﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace ConsoleAppDemo.ThreadDemo
{
    public class Account
    {
        private readonly object _thislock = new object();
        int _balance;
        private Random r = new Random();

        public int i = 0;

        public Account(int money)
        {
            _balance = money;
        }

        void WithDraw(int cost)
        {
            Console.WriteLine(i);
            if (_balance < 0)
            {
                throw new Exception("Negative Balance");
            }
            lock (_thislock)
            {
                if (_balance >= cost)
                {
                    Console.WriteLine("Amount to Withdraw        : -" + cost);
                    _balance = _balance - cost;
                    Console.WriteLine("{0}__Balance after Withdrawal  : {1} ", i, _balance);
                    i++;
                }
                Console.WriteLine(i);
            }
        }

        public int Count
        {
            get { return i; }
        }

        public void DoTransactions()
        {
//            for (int i = 0; i < 10; i++)
//            {
                WithDraw(1);
//            }
        }
    }

    public class AccountEntry
    {
        public static void Entry()
        {
            var tlist = new Thread[10];
            var account = new Account(100);
            for (int i = 0; i < 10; i++)
            {
                var t = new Thread(account.DoTransactions);
                tlist[i] = t;
            }
            for (int i = 0; i < 10; i++)
            {
                tlist[i].Start();
            }
            Console.WriteLine("Account Count:{0}", account.Count);

        }
    }
}
